// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj

const internal = require("stream")

// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
	/**
	 * getData 获取数据
	 */
	async getData() {
		try {
			const db = uniCloud.databaseForJQL({
				clientInfo: this.getClientInfo()
			})
			return await db.collection('opendb-mall-categories').get({
				getTree: {}
			})
		} catch (err) {
			return {
				errCode: 'ERROR',
				errMsg: '错误',
				errInfo: err
			}
		}

	},
	/**
	 * addData 新增数据
	 * @param {object} params 传参
	 */
	async addData(params) {
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		try {
			const db = uniCloud.databaseForJQL({
				clientInfo: this.getClientInfo()
			})
			return await db.collection('opendb-mall-categories').add(params)
		} catch (err) {
			return {
				errCode: 'ERROR',
				errMsg: '错误',
				errInfo: err
			}
		}

	},
	/**
	 * updateData 更新数据
	 * @param {object} params 传参
	 */
	async updateData(params) {
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		const {
			_id,
			data
		} = params || {}
		if (!_id) {
			return {
				errCode: 'ID_IS_NULL',
				errMsg: '_id不能为空'
			}
		}
		try {
			const db = uniCloud.database()
			return await db.collection('opendb-mall-categories').doc(
				_id
			).set({
				create_date: data?.create_date,
				parent_id: data?.parent_id,
				icon: data?.icon,
				title: data?.title
			})
		} catch (err) {
			return {
				errCode: 'ERROR',
				errMsg: '错误',
				errInfo: err
			}
		}

	},
	/**
	 * deleteData 删除数据
	 * @param {object} params 传参
	 */
	async deleteData(params) {
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		const {
			_id
		} = params || {}
		if (!_id) {
			return {
				errCode: 'PARAM_IS_ERROR',
				errMsg: '_id不能为空'
			}
		}
		try {
			const db = uniCloud.databaseForJQL({
				clientInfo: this.getClientInfo()
			})
			// 删除商品数据
			await db.collection('opendb-mall-goods').where(db.command.or({
				category_id: _id
			}, {
				category_parent_id: _id
			})).remove()
			// 删除分类数据
			return await db.collection('opendb-mall-categories').where(db.command.or({
				_id
			}, {
				parent_id: _id
			})).remove()
		} catch (err) {
			return {
				errCode: 'ERROR',
				errMsg: '错误',
				errInfo: err
			}
		}

	}
}